package com.lianlianche.arch.jetpack.ktx

import android.annotation.SuppressLint
import android.content.Context
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

/**
 * <pre>
 *     @author : Ly
 *     e-mail  : 972223177@qq.com
 *     time    : 2019/9/19
 *     desc    : 属性代理，sharePreference 拓展
 *     version : 1.0
 * </pre>
 */

class Preference <T>(val context: Context,val name:String,val default:T,val preName:String="action_piker"):ReadWriteProperty<Any?,T>{

    private val prefs by lazy {
        context.getSharedPreferences(preName,Context.MODE_PRIVATE)
    }

    override fun getValue(thisRef: Any?, property: KProperty<*>): T {
        return findPreference(findProperName(property))
    }

    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        putPreference(findProperName(property),value)
    }

    private fun findProperName(property:KProperty<*>) =if (name.isEmpty()) property.name else name

    @Suppress("UNCHECKED_CAST")
    private fun findPreference(key:String):T{
        return when(default){
            is Long -> prefs.getLong(key,default)
            is Int -> prefs.getInt(key,default)
            is Boolean -> prefs.getBoolean(key,default)
            is String -> prefs.getString(key,default)
            else -> throw  IllegalArgumentException("argument type error")
        } as T
    }

    @SuppressLint("CommitPrefEdits")
    private fun putPreference(key:String, value: T){
        with(prefs.edit()){
            when(value){
                is Long -> putLong(key,value)
                is Int ->putInt(key,value)
                is Boolean ->putBoolean(key,value)
                is String -> putString(key,value)
                else -> throw  IllegalArgumentException("argument type error")
            } .apply()
        }
    }

}